package com.cassio.stores.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.cassio.stores.MainApplication;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "database.db";
    private static SQLiteOpenHelper instance;

    private DBHelper() {
        super(MainApplication.getContext(), DATABASE_NAME, null, DATABASE_VERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
        	executeSqlScript(db, "CREATE_DATABASE.sql");
        	executeSqlScript(db, "DUMP_DATA.sql");
		} catch (IOException e) {
			Log.e(AppConstants.LOG_TAG, "Error creating the database", e);
		}
    }

	
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    	try {
    		executeSqlScript(db, "DROP_DATABASE.sql");
		} catch (IOException e) {
			Log.e(AppConstants.LOG_TAG, "Error erasing the database", e);
		}

        onCreate(db);
    }

	public static SQLiteOpenHelper getInstance() {
		if(instance == null)
			instance = new DBHelper();
			
		return instance;
	}
	
	private void executeSqlScript(SQLiteDatabase db, String fileName) throws IOException {
		InputStream stream = MainApplication.getContext().getApplicationContext().getAssets().open(fileName);
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		String line = br.readLine();
		while (line != null){
			if (line.length() > 0) {
				db.execSQL(line);
			}
			line = br.readLine();
		}
	}
}
